package com.drinks.yiniang.ui.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.listview.PayPasswordKeyBoardAdapter;
import com.drinks.yiniang.common.help.PayManager;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.entity.user.UserSetJson;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.ui.activity.user.setting.ForgotPaymentPasswordActivity;
import com.drinks.yiniang.ui.widget.layout.HandMoveSwipeLayout;
import com.drinks.yiniang.ui.widget.textview.PayPasswordView;
import com.drinks.yiniang.utils.SharedPreUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.widget.dialog.BaseDialogFragment;
import com.hansen.library.ui.widget.layout.ImageTextArrowLayout;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;

/**
 * Created by han on 2018/10/30 0030.
 */

public class PayDialog extends BaseDialogFragment implements View.OnClickListener, PayPasswordView.OnPasswordInputCompleteListener,
        AdapterView.OnItemClickListener, HandMoveSwipeLayout.OnSwipeChangeListener {

    private final static int NUMBER_BUTTON_DELETE = 11;//删除
    private final static int NUMBER_BUTTON_ZERO = 10;//0号按键
    private final static int NUMBER_BUTTON_CLEAR = 9;//清除按键

    private Context mContext;
    //关闭
    private ImageView iv_pay_dialog_close;
    private HandMoveSwipeLayout ll_pay_dialog_swipe;
    //钱包支付
    private ImageTextArrowLayout ll_dialog_wallet_pay;
    //微信支付
    private ImageTextArrowLayout ll_dialog_wx_pay;
    //支付宝支付
    private ImageTextArrowLayout ll_dialog_ali_pay;
    //右边view
    private ImageView iv_pay_pwd_close;
    //输入密码框
    private PayPasswordView tv_pay_pwd;
    //忘记密码
    private TextView tv_pay_forgot_pwd;
    //输入键盘
    private GridView gv_pay_pwd_keyboard;

    private PayPasswordKeyBoardAdapter mPwdKeyBoardAdapter;

    private OnPayListener onPayListener;

    //是否显示钱包
    private boolean isShowWalletPay = true;

    private int mCurrentPayType;

    public static PayDialog newInstance() {
        return newInstance("", true);
    }

    public static PayDialog newInstance(boolean isShowWalletPay) {
        return newInstance("", isShowWalletPay);
    }

    public static PayDialog newInstance(String payMoney) {
        return newInstance(payMoney, true);
    }

    public static PayDialog newInstance(String payMoney, boolean isShowWalletPay) {
        PayDialog dialogFragment = new PayDialog();

        Bundle args = new Bundle();

        //钱包余额
        args.putString(Constants.KeyMoney, payMoney);
        args.putBoolean(Constants.KeyShow, isShowWalletPay);

        dialogFragment.setArguments(args);

        return dialogFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            if (getParentFragment() != null) {
                onPayListener = (OnPayListener) getParentFragment();
            } else {
                onPayListener = (OnPayListener) context;
            }
        } catch (ClassCastException e) {
            LogUtils.e(context.toString() + " must implement OnPayListener");
        }
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mContext = getActivity();

        LayoutInflater inflater = this.getActivity().getLayoutInflater();

        View mView = inflater.inflate(R.layout.dialog_pay, null);

        Dialog dialog = new Dialog(this.getActivity(), R.style.PayDialogStyle);

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(mView);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);

        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.LEFT | Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();

        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.dimAmount = 0.5f;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平

        dialogWindow.setAttributes(lp);
        dialogWindow.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        initLeftView(mView);
        initRightView(mView);
        initData();

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });

        return dialog;
    }

    private void initLeftView(View mView) {
        iv_pay_dialog_close = mView.findViewById(R.id.iv_pay_dialog_close);

        ll_pay_dialog_swipe = mView.findViewById(R.id.ll_pay_dialog_swipe);

        ll_dialog_wallet_pay = mView.findViewById(R.id.ll_dialog_wallet_pay);
        ll_dialog_wx_pay = mView.findViewById(R.id.ll_dialog_wx_pay);
        ll_dialog_ali_pay = mView.findViewById(R.id.ll_dialog_ali_pay);

        iv_pay_dialog_close.setOnClickListener(this);
        ll_dialog_wallet_pay.setOnClickListener(this);
        ll_dialog_ali_pay.setOnClickListener(this);
        ll_dialog_wx_pay.setOnClickListener(this);
    }

    private void initRightView(View mView) {
        iv_pay_pwd_close = mView.findViewById(R.id.iv_pay_pwd_close);

        tv_pay_pwd = mView.findViewById(R.id.tv_pay_pwd);
        tv_pay_forgot_pwd = mView.findViewById(R.id.tv_pay_forgot_pwd);

        gv_pay_pwd_keyboard = mView.findViewById(R.id.gv_pay_pwd_keyboard);

        iv_pay_pwd_close.setOnClickListener(this);
        tv_pay_forgot_pwd.setOnClickListener(this);
        tv_pay_pwd.setOnPasswordCompleteLinstener(this);
        gv_pay_pwd_keyboard.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_pay_dialog_close://关闭
                if(onPayListener != null) {
                    onPayListener.onPayClose();
                }
                dismiss();
                break;
            case R.id.ll_dialog_wallet_pay://钱包支付
                setCheckResourse(PayManager.PAY_CHANNEL_WALLET);
                doIsOpenPayPassword();
                break;
            case R.id.ll_dialog_ali_pay://支付宝支付
                setCheckResourse(PayManager.PAY_CHANNEL_ALIPAY);
                if (onPayListener != null) {
                    onPayListener.onPayClick(PayManager.PAY_CHANNEL_ALIPAY);
                }
                dismiss();
                break;
            case R.id.ll_dialog_wx_pay://微信支付
                setCheckResourse(PayManager.PAY_CHANNEL_WX);
                if (onPayListener != null) {
                    onPayListener.onPayClick(PayManager.PAY_CHANNEL_WX);
                }
                dismiss();
                break;
            case R.id.iv_pay_pwd_close://关闭
                ll_pay_dialog_swipe.closeSwipe();
                break;
            case R.id.tv_pay_forgot_pwd://忘记密码
                mContext.startActivity(new Intent(mContext, ForgotPaymentPasswordActivity.class));
                break;
            default:
                break;
        }
    }

    protected void initData() {
        if (getArguments() != null) {
            isShowWalletPay = getArguments().getBoolean(Constants.KeyShow, true);
        }

        ll_dialog_wallet_pay.setArrowImageVisibility(false);
        ll_dialog_ali_pay.setArrowImageVisibility(false);
        ll_dialog_wx_pay.setArrowImageVisibility(false);

        ll_dialog_wallet_pay.setVisibility(isShowWalletPay ? View.VISIBLE : View.GONE);

        ll_pay_dialog_swipe.setOnSwipeChangeListener(this);
    }

    private void initKeyboardData() {
        if (mPwdKeyBoardAdapter == null) {
            mPwdKeyBoardAdapter = new PayPasswordKeyBoardAdapter(mContext);

            gv_pay_pwd_keyboard.setAdapter(mPwdKeyBoardAdapter);
        }
    }

    private void setCheckResourse(int payType) {
        if (mCurrentPayType == payType) {
            return;
        }

        switch (mCurrentPayType) {//check true->false
            case PayManager.PAY_CHANNEL_WALLET://钱包支付
                ll_dialog_wallet_pay.setArrowImageVisibility(false);
                break;
            case PayManager.PAY_CHANNEL_ALIPAY://支付宝支付
                ll_dialog_ali_pay.setArrowImageVisibility(false);
                break;
            case PayManager.PAY_CHANNEL_WX://微信支付
                ll_dialog_wx_pay.setArrowImageVisibility(false);
                break;
            default:
                break;
        }

        switch (payType) {//check false->true
            case PayManager.PAY_CHANNEL_WALLET://钱包支付
                ll_dialog_wallet_pay.setArrowImageVisibility(true);
                break;
            case PayManager.PAY_CHANNEL_ALIPAY://支付宝支付
                ll_dialog_ali_pay.setArrowImageVisibility(true);
                break;
            case PayManager.PAY_CHANNEL_WX://微信支付
                ll_dialog_wx_pay.setArrowImageVisibility(true);
                break;
            default:
                break;
        }

        mCurrentPayType = payType;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (onPayListener != null) {
            onPayListener.onPayDismiss();
        }
    }

    @Override
    public void dismiss() {
        //super.dismiss();
        dismissAllowingStateLoss();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String password = tv_pay_pwd.getText().toString();

        if (position == NUMBER_BUTTON_CLEAR) {
            password = "";
        } else if (position == NUMBER_BUTTON_DELETE) {
            if (password.length() > 0) {
                password = password.substring(0, password.length() - 1);
            }
        } else {
            if (position == NUMBER_BUTTON_ZERO) {
                password += "0";
            } else {
                password += (position + 1);
            }
        }

        tv_pay_pwd.setText(password);
    }

    @Override
    public void onComplete() {
        doPayPasswordVerify();
    }

    @Override
    public void onSwipeChange(boolean isOpen) {

    }

    //验证支付密码
    private void doPayPasswordVerify() {
        final String password = StringUtils.getTextViewText(tv_pay_pwd.getText());

        if (StringUtils.isEmpty(password) || password.length() != 6) {
            ToastUtils.showShort(R.string.text_hint_input_payment_password);
            return;
        }

        showLoadingDialog();

        UserApiIO.getInstance().doPayPasswordVerify(password, new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                if (onPayListener != null) {
                    onPayListener.onPayClick(PayManager.PAY_CHANNEL_WALLET);
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //钱包支付验证是否开启了输入支付密码
    private void doIsOpenPayPassword() {
        String isOpenPayPassword = SharedPreUtils.getInstance().getIsOpenPayPassword();

        if (StringUtils.isEmpty(isOpenPayPassword)) {//为空需要通过接口获取
            showLoadingDialog();

            UserApiIO.getInstance().getUserSetData(new APIRequestCallback<UserSetJson, Tuple2<Integer, String>>() {
                @Override
                public void onSuccess(UserSetJson res) {
                    SharedPreUtils.getInstance().saveIsOpenPayPasswordID(Constants.STATUS_GLOBAL_YES.equals(res.getData().getOpen_pay()) ? Constants.STATUS_GLOBAL_YES : Constants.STATUS_GLOBAL_NO);

                    judgeIsShowPassword(res.getData().getOpen_pay());
                }

                @Override
                public void onError(Tuple2<Integer, String> error) {
                    ToastUtils.showShort(error._2);
                }

                @Override
                public void onComplete() {
                    dismissDialog();
                }
            });

            return;
        }

        judgeIsShowPassword(isOpenPayPassword);
    }

    private void judgeIsShowPassword(String isOpenPayPassword) {
        if (Constants.STATUS_GLOBAL_YES.equals(isOpenPayPassword)) {
            tv_pay_pwd.setText("");
            initKeyboardData();
            ll_pay_dialog_swipe.openSwipe();
        } else {
            if (onPayListener != null) {
                onPayListener.onPayClick(PayManager.PAY_CHANNEL_WALLET);
            }
        }
    }

    @Override
    public void onDestroy() {
        onPayListener = null;
        super.onDestroy();
    }

    public interface OnPayListener {
        void onPayClick(int payType);
        void onPayDismiss();
        void onPayClose();
    }
}

